<template>
  <div
    class="kogbox"
    v-loading="loading"
    element-loading-text=""
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
  >
    <div>
      <navs :isDark="true"></navs>
      <div class="cont">
        <img src="../assets/image/home/home2.png" class="home2" alt="" />
        <div class="flex-ct">
          <div
            v-for="(rsc, index) in rscItems"
            :key="index"
            class="rsc-item"
            :class="{ active: selectedRsc === index }"
            @click="selectRsc(index)"
          >
            {{ rsc }}
          </div>
        </div>
        <div class="flex-ct listbox">
          <div
            v-for="(item, i) in filterNFTsByType(list, selectedRsc + 1)"
            :key="i"
          >
            <img :src="getImageUrl(i)" class="itemimg" alt="" />
            <div>
              {{ $t("nft.output") }}：{{ getweeweb3(item.totalReward) }} AIME
            </div>
            <div>
              {{ $t("nft.pending") }}：{{ getweeweb3(item.unClaimedReward) }}
              AIME
            </div>
            <div>{{ $t("nft.quota") }}：{{ getweeweb3(item.power) }} U</div>
            <div></div>
            <div class="flex-ct btn">
              <div @click="synthesis(item, 1)">{{ $t("nft.exchange") }}</div>
              <div
                v-if="item.nftType == 1 && item.power == 0"
                @click="synthesis"
              >
                {{ $t("nft.exchange") }}
              </div>
              <div v-if="item.nftType == 2" @click="synthesis(item, 2)">
                {{ $t("nft.synthesis") }}AIME-NFT2
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- <foot></foot> -->
    </div>
  </div>
</template>

<script>
import navs from "../components/nav.vue";
import foot from "./components/foot.vue";
import {
  AIMEMainContract,
  web3,
  AIMEMainAddress,
  USDTContract,
  USDTAddress,
  AIMENFTContract,
} from "@/assets/js/web3.js";
import { Toast } from "vant";

export default {
  components: {
    navs,
    foot,
  },
  data() {
    return {
      rscItems: ["AIME-ONE", "AIME-TWO", "AIME-THREE"],
      selectedRsc: 0,
      list: [],
      nft2Reward: 0,
      nft3Reward: 0,
      loading: false,
      leaderAddress: "",
      currentAccount: "",
    };
  },
  computed: {
    // currentAccount() {
    //   return sessionStorage.getItem("account") || "";
    // },
    // leaderAddress() {
    //   return sessionStorage.getItem("leaderAddress") || "";
    // },
  },

  async mounted() {
    this.currentAccount = sessionStorage.getItem("account") || "";
    this.leaderAddress = sessionStorage.getItem("leaderAddress") || "";
    this.getLsit();
    this.getAccountData();
  },
  methods: {
    //提现
    async Withdrawal(item) {
      this.loading = true;
      try {
        //3.claimNftRewards(uint256 tokenId)：领取NFT收益，tokenId-NFT编号。
        if (item.unClaimedReward == 0) {
          return Toast(this.$t("nft.noReward"));
        }

        let res = await AIMEMainContract.methods
          .claimNftRewards(item.tokenId)
          .send({ from: this.currentAccount });

        if (res) {
          Toast(this.$t("nft.withdrawSuccess"));
        }
        this.loading = false;
      } catch (error) {
        Toast(error);
        this.loading = false;
      }
    },
    getweeweb3(sun) {
      let srrs = Number(web3.utils.fromWei(sun, "ether")).toFixed(2);
      return srrs;
    },
    async getAccountData() {
      if (!this.currentAccount) return;
      try {
        const res = await AIMEMainContract.methods
          .queryUserAccountData(this.currentAccount)
          .call();

        this.nft2Reward = res.nft2Reward;
        this.nft3Reward = res.nft3Reward;
      } catch (e) {
        console.error("合约调用失败", e);
      }
    },
    //合成
    async synthesis(item, index) {
      try {
        this.loading = true;

        if (index == 1) {
          if (this.nft2Reward != 0) {
            return Toast(this.$t("nft.claimFirst"));
          }
          console.log(this.leaderAddress, "this.leaderAddress");
          console.log(item.tokenId, "item.tokenId");
          await AIMENFTContract.methods
            .approve(AIMEMainAddress, item.tokenId)
            .send({ from: this.currentAccount });
          let res = await AIMEMainContract.methods
            .mergeNft2(this.leaderAddress, item.tokenId)
            .send({ from: this.currentAccount });

          if (res) {
            Toast(this.$t("nft.mergeSuccess"));
            this.loading = false;
          }
        } else {
          if (this.nft3Reward != 0) {
            return Toast(this.$t("nft.claimFirst"));
          }
          this.loading = true;
          const MAX_APPROVE_AMOUNT = web3.utils.toWei("1000000", "ether"); // 授权100万个单位，足够大
          await AIMENFTContract.methods
            .approve(AIMEMainAddress, item.tokenId)
            .send({ from: this.currentAccount });
          // await USDTContract.methods
          //   .approve(AIMEMainAddress, MAX_APPROVE_AMOUNT)
          //   .send({ from: this.currentAccount });

          let res = await AIMEMainContract.methods
            .mergeNft3(this.leaderAddress, item.tokenId)
            .send({ from: this.currentAccount });

          if (res) {
            Toast(this.$t("nft.mergeSuccess"));
            this.loading = false;
          }
        }
      } catch (error) {
        console.log(error, "item.error");

        Toast(error);
        this.loading = false;
      }
    },
    getImageUrl() {
      return require(`@/assets/image/nft/${this.selectedRsc}.png`);
    },
    selectRsc(index) {
      this.selectedRsc = index;
    },
    filterNFTsByType(nftArray, nftType) {
      // 过滤出指定类型的 NFT
      const filteredNFTs = nftArray.filter((nft) => nft.nftType == nftType);
      // 展示过滤后的结果
      // console.log(`NFT 类型为 ${nftType} 的列表:`);
      filteredNFTs.forEach((nft) => {
        console.log(`ID: ${nft.id}, 名称: ${nft.name}`);
      });
      return filteredNFTs; // 如果需要展示结果，可以返回此数组
    },
    //8.getUserNfts(address account)：查询我的NFT列表。返回值：_NFT对象数组，字段：tokenId-NFT的编号，nftType-NFT类型（1，2，3），power-剩余算力（针对AIMENFT1，有算力代币未出局，AIMENFT2、AIMENFT3算力均为0），unClaimedReward-待领取收益。
    async getLsit() {
      console.log(this.currentAccount, "this.currentAccount");

      try {
        let res = await AIMEMainContract.methods
          .getUserNfts(this.currentAccount)
          .call();
        this.list = res;
      } catch (error) {
        console.log(error, "error");
      }
    },
  },
};
</script>
<style lang="less" scoped>
.cont {
  padding: 0 36px 160px;
  background: #121212;
  font-weight: 500;
  font-size: 28px;
  color: #a1a1a1;
  .home2 {
    width: 100%;
    margin: 64px 0;
  }
  .rsc-item {
    padding: 20px 16px;
  }
  .active {
    font-weight: 500;
    font-size: 28px;
    color: #bdee63;
    border-bottom: 2px solid #bdee63;
  }
}
.listbox {
  flex-wrap: wrap;
  min-height: 300px;
  //   padding: 64px 0;
  .itemimg {
    width: 318px;
    height: 318px;
    margin: 58px 0 24px;
  }
  .btn {
    gap: 18px;
    font-weight: 500;
    font-size: 28px;
    text-align: center;
    margin-top: 20px;
    > div {
      flex: 1;
      padding: 14px 0;
    }
    :nth-child(1) {
      color: #bdee63;
      border-radius: 12px 12px 12px 12px;
      border: 2px solid #bdee63;
    }
    :nth-child(2) {
      color: #121113;
      background: #bdee63;
      box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.05);
      border-radius: 12px;
    }
  }
}
</style>
